import React, { useState, useEffect } from "react";
import { Input, Card, Button, Modal, Form, InputNumber, message } from "antd";
import { useStore } from "../../../stores/store.jsx"; // 引入 store
import { updateExpectationApi } from "../../../api/jobSeeker"; // 引入 API

const SearchAndFilter = ({ onSearch }) => {
  const { state, dispatch } = useStore(); // 从 store 中获取 state 和 dispatch
  const [searchTerm, setSearchTerm] = useState(""); // 保存搜索关键字
  const [isFixed, setIsFixed] = useState(false); // 控制是否固定定位
  const [isModalVisible, setIsModalVisible] = useState(false); // 控制弹窗显示
  const [form] = Form.useForm();

  // 从 store 中获取求职期望
  const expectation = state.userInfo?.expectation || {
    job_name: "",
    money: 0,
    place: "",
    industry: "",
  };

  // 处理搜索输入变化并实时触发过滤
  const handleInputChange = (e) => {
    const value = e.target.value;
    setSearchTerm(value);
    onSearch(value.trim()); // 实时调用父组件的回调函数
  };

  // 监听滚动事件
  useEffect(() => {
    const handleScroll = () => {
      const searchBoxTop = 30; // 距离顶部导航栏的初始距离
      if (window.scrollY > searchBoxTop) {
        setIsFixed(true); // 转化为固定定位
      } else {
        setIsFixed(false); // 恢复正常定位
      }
    };

    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  // 打开编辑求职期望弹窗
  const handleEditClick = () => {
    form.setFieldsValue(expectation); // 设置表单初始值
    setIsModalVisible(true);
  };

  // 确认弹窗
  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();

      // 调用更新 API
      await updateExpectationApi({
        job_name: values.job_name,
        money: parseInt(values.money, 10),
        place: values.place,
        industry: values.industry,
      });

      // 更新全局状态
      dispatch({
        type: "SET_USER_INFO",
        payload: {
          ...state.userInfo,
          expectation: values,
        },
      });

      message.success("求职期望更新成功");
      setIsModalVisible(false);
    } catch (error) {
      console.error("更新求职期望失败:", error);
      message.error(error.response?.data?.message || "更新失败，请重试");
    }
  };

  // 取消弹窗
  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <div
      style={{
        position: isFixed ? "fixed" : "relative", // 切换定位方式
        top: isFixed ? "60px" : "0", // 距离顶部的距离
        zIndex: isFixed ? 1000 : "auto", // 固定定位时提高层级
        width: "100%", // 保持宽度不变
        maxWidth: "1000px", // 设置最大宽度
        background: "#fff", // 确保背景色
        boxShadow: isFixed ? "0 2px 6px rgba(0, 0, 0, 0.1)" : "none", // 滚动时添加阴影
        padding: "16px", // 内边距
        borderRadius: "6px", // 圆角
      }}
    >
      {/* 搜索框 */}
      <div style={{ marginBottom: "16px" }}>
        <Input
          placeholder="搜索职位、公司"
          value={searchTerm}
          onChange={handleInputChange}
          style={{
            borderRadius: "20px",
            padding: "10px 15px",
            flex: 1,
            border: "2px solid transparent", // 默认无边框
            transition: "border-color 0.3s ease", // 添加过渡效果
            boxShadow: "0 0 0 1px transparent", // 默认无边框阴影
          }}
          onMouseEnter={(e) => {
            e.target.style.borderColor = "#ff6400"; // 鼠标悬停时边框变为橙色
          }}
          onMouseLeave={(e) => {
            e.target.style.borderColor = "transparent"; // 鼠标移开时恢复默认
          }}
        />
      </div>

      {/* 筛选卡片 */}
      <Card
        style={{
          borderRadius: "6px",
          boxShadow: "0 2px 6px rgba(0, 0, 0, 0.1)",
        }}
      >
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <div>
            <h3 style={{ margin: 0, color: "#ff6a00" }}>
              {expectation.job_name || "未设置职位"}
            </h3>
            <p style={{ margin: 0, color: "#888" }}>
              {expectation.industry || "未设置行业"} |{" "}
              {expectation.place || "未设置地点"} | {expectation.money || 0}k/月
            </p>
          </div>
          <Button
            type="link"
            onClick={handleEditClick}
            style={{ color: "#ff6a00" }}
          >
            编辑求职期望
          </Button>
        </div>
      </Card>

      {/* 弹窗 */}
      <Modal
        title="编辑求职期望"
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        okText="确定"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="期望职位"
            name="job_name"
            rules={[{ required: true, message: "请输入期望职位" }]}
          >
            <Input placeholder="请输入期望职位" />
          </Form.Item>
          <Form.Item
            label="期望地点"
            name="place"
            rules={[{ required: true, message: "请输入期望地点" }]}
          >
            <Input placeholder="请输入期望地点" />
          </Form.Item>
          <Form.Item
            label="期望行业"
            name="industry"
            rules={[{ required: true, message: "请输入期望行业" }]}
          >
            <Input placeholder="请输入期望行业" />
          </Form.Item>
          <Form.Item
            label="期望薪资 (k/月)"
            name="money"
            rules={[{ required: true, message: "请输入期望薪资" }]}
          >
            <InputNumber
              placeholder="请输入期望薪资"
              min={0}
              style={{ width: "100%" }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SearchAndFilter;
